<template>
  <div>
    <van-row type="flex" justify="center" class="deep">
      <van-col span="20">
        <van-field
          v-model="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="newPassword"
          type="password"
          label="确认密码"
          placeholder="请输入确认密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <p class="reg" @click="goLogin">返回登录页</p>
        <van-button color="#f50a00" block @click="regist">注册</van-button>
      </van-col>
    </van-row>
  </div>
</template>

<script>
export default {
  name: "Regist",

  data() {
    return {
      username: "",
      password: "",
      newPassword: "",
      user_img: "",
    };
  },

  mounted() {},

  methods: {
    goLogin() {
      this.$router.push({
        path: "/login",
      });
    },
    regist() {
      this.$axios
        .get("/users?username=" + this.username)
        .then((res) => {
          console.log(res);
          if (res.data.length == 0) {
            if (this.password != this.newPassword) {
              this.$toast("两次输入的密码不一样");
            } else {
              let data = {
                username: this.username,
                password: this.password,
                user_img: this.user_img,
              };
              console.log(data);
              this.$axios
                .post("/users", data)
                .then((res) => {
                  // console.log(res);
                  if (res.statusText == "Created") {
                    this.$dialog
                      .alert({
                        title: "提示",
                        message: "注册成功，请登录",
                      })
                      .then(() => {
                        this.$router.push("/");
                      });
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          } else {
            this.$dialog({ message: "该用户已存在，不允许注册" });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style scoped>
.deep /deep/ .van-button{
  border-radius: 45px;
}
</style>